package com.carkeeper.common.interceptor;


import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;

/**
 * feign拦截器，只要请求就会拦截
 * @author Administrator
 */
@Component
public class FeignInterceptor implements RequestInterceptor {
    /**
     * 微服务之间的认证
     * @param requestTemplate
     */
    @Override
    public void apply(RequestTemplate requestTemplate) {

        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();

        if (requestAttributes != null) {

            HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
            if (request != null) {

                Enumeration<String> headerNames = request.getHeaderNames();

                if (headerNames != null) {
                    while (headerNames.hasMoreElements()) {

                        String headerName = headerNames.nextElement();

                        if ("authorization".equalsIgnoreCase(headerName)) {
                            String headerValue = request.getHeader(headerName);

                            requestTemplate.header(headerName, headerValue);
                        }
                    }
                }

            }
        }

    }
}